package wassalt.client;



import java.io.IOException;

import org.apache.http.HttpStatus;

import wassalt.Utils.AppConstants;
import wassalt.Utils.StatusBarNotification;
import wassalt.Utils.User;
import wassalt.Utils.ClientServerCommunication;

import com.google.android.c2dm.C2DMBaseReceiver;

import android.content.Context;
import android.content.Intent;

import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;

public class C2DMReceiver extends C2DMBaseReceiver {
	
	private static String KEY = "c2dmPref";
	
	public C2DMReceiver() {
		super(AppConstants.SENDER_ID);
	}

	/**
	 * Called when a registration token has been received.
	 * 
	 * @param context
	 *            the Context
	 * @param registrationId
	 *            the registration id as a String
	 * @throws IOException
	 *             if registration cannot be performed
	 */
	@Override
	public void onRegistered(Context context, String registration) {
		Log.d("c2dm ser",registration);
		handleRegistration(context, registration);
	}

	/**
	 * Called when the device has been unregistered.
	 * 
	 * @param context
	 *            the Context
	 */
	@Override
	public void onUnregistered(Context context) {
		handleRegistration(context, null);
	}

	/**
	 * Called on registration error. This is called in the context of a Service
	 * - no dialog or UI.
	 * 
	 * @param context
	 *            the Context
	 * @param errorId
	 *            an error message, defined in {@link C2DMBaseReceiver}
	 */
	@Override
	public void onError(Context context, String errorId) {
		Log.e("c2dm on Error",errorId);
		Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE)
				.edit();
		editor.remove(AppConstants.DEVICE_REG_KEY);
		editor.commit();
		Intent broadCastIntent = new Intent(AppConstants.C2DM_RESPONSE_FILTER);
		// Using the http statuses to express Failure
		broadCastIntent.putExtra(AppConstants.HTTP_STATUS,
				HttpStatus.SC_NOT_FOUND);
		sendBroadcast(broadCastIntent);
	}

	/**
	 * Called when a cloud message has been received.
	 */
	@Override
	public void onMessage(Context context, Intent intent) {
		
		
		Log.e("***Reciever","intent received" );
		 Bundle extras = intent.getExtras();
         if (extras != null) {
            //parse the message and do something with it.
            //For example, if the server sent the payload as "data.message=xxx", here you would have an extra called "message"
            String message = extras.getString("message");
            Log.i("Message", "received message: " + message);
            handleMessage(message, context);
         }
	}

	private void handleRegistration(Context context, String registration) {

		if (registration != null) {
			Log.d("c2dm Key", registration);
			Editor editor = context.getSharedPreferences(KEY,
					Context.MODE_PRIVATE).edit();
			editor.putString(AppConstants.DEVICE_REG_KEY, registration);
			editor.commit();			
			// Sending key to the server
			User.updateDeviceID(this, registration);
		}
	}

	/**
	 * Chooses the appropriate response according to the message received
	 * @author Aya Kamel
	 * @param msg
	 * 			The message body
	 * @param context
	 * 			The current application context
	 */
	private void handleMessage(String msg, Context context) {
		// Do whatever you want with the message
        if (msg.equals( AppConstants.WELCOME_MSG))
       	 	StatusBarNotification.show(this,getString(R.string.app_name) , getString(R.string.reg_succ));
		
        //When a change occurs in the incoming table
        if(msg.equals(AppConstants.CHANGE_INCOMING_MSG))
        	ClientServerCommunication.refreshIncomingNotifications(context);
        
        //When a change occurs in the outgoing table
		if(msg.equals(AppConstants.CHANGE_OUTGOING_MSG))
			ClientServerCommunication.refreshOutgoingNotifications(context);
		
		//When a change occurs in the self notifications table
		if(msg.equals(AppConstants.CHANGE_SELF_MSG))
			ClientServerCommunication.refreshSelfNotifications(context);
		
		//When a notification for me is fulfilled
		if(msg.equals(AppConstants.NEW_ARRIVAL_MSG))
			ClientServerCommunication.getArrivals(context);
		
		//When i receive a new request
		if(msg.equals(AppConstants.NEW_REQUEST_MSG))
			ClientServerCommunication.getNewRequest(context);
	}

}